package com.peng._05weibo.common.error;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.Servlet;
import org.apache.catalina.startup.Tomcat;
import org.apache.catalina.valves.ErrorReportValve;
import org.apache.coyote.UpgradeProtocol;
import org.springframework.beans.BeansException;
import  org.springframework.beans.factory.config.BeanPostProcessor;
import  org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import  org.springframework.boot.autoconfigure.web.embedded.TomcatWebServerFactoryCustomizer;
import  org.springframework.boot.web.embedded.tomcat.ConfigurableTomcatWebServerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * 自定义404页面
 * @Author peng
 * @Date 2024-04-23 14:14
 */
@ConditionalOnClass({ Servlet.class, Tomcat.class,  UpgradeProtocol.class,  TomcatWebServerFactoryCustomizer.class })
@Component
@Slf4j
public class TomcatCustomizerBeanPostProcessor implements  BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object  bean, String beanName) throws BeansException {
        if (bean instanceof  ConfigurableTomcatWebServerFactory) {
            ConfigurableTomcatWebServerFactory  configurableTomcatWebServerFactory =  (ConfigurableTomcatWebServerFactory) bean;

            addTomcat404CodePage(configurableTomcatWebServerFactory);
        }
        return  BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
    private static void  addTomcat404CodePage(ConfigurableTomcatWebServerFactory  factory) {
        factory.addContextCustomizers((context) -> {
            String tomcatTempPath =  context.getCatalinaBase().getPath();
            log.info("tomcat目录：{}", tomcatTempPath);
            String path = tomcatTempPath + "/404.html";
            ClassPathResource cr = new  ClassPathResource("static/404.html");
            if (cr.exists()) {
                File file404 = new File(path);
                if (!file404.exists()) {
                    try {
                        FileCopyUtils.copy(cr.getInputStream(), new FileOutputStream(file404));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            ErrorReportValve valve = new  ErrorReportValve();
            valve.setProperty("errorCode.404", path);
            valve.setShowServerInfo(false);
            valve.setShowReport(false);
            valve.setAsyncSupported(true);
            context.getParent().getPipeline().addValve(valve);
        });
    }
}
